#ifndef TCPCONNECTION_H
#define TCPCONNECTION_H
#include "inetaddress.hpp"
#include "socket.hpp"
#include "socketio.hpp"
#include <memory>
#include <string>
#include <functional>
using std::string;
namespace moqi
{
class TcpConnection;
using TcpConnectionPtr = std::shared_ptr<TcpConnection>;
using TcpConnectionCallback = std::function<void(TcpConnectionPtr)>;

class TcpConnection:
public std::enable_shared_from_this<TcpConnection>
    

{
public:
    TcpConnection(int fd);
    ~TcpConnection();
    void send(const string& msg)const;
    string recv();
    void shutdown();
    bool isClosed()const;
    string status()const;
#if 0
    void setAllCallback(TcpConnectionCallback &&cb1,
                        TcpConnectionCallback &&cb2,
                        TcpConnectionCallback &&cb3
                        )
    {
        _onConnecton = std::move(cb1);
        _onMessage =  std::move(cb2);
        _onClose = std::move(cb3);
    }
#endif
#if 1
    //此处必须使用拷贝，若使用移动语义，会将函数的所有权转移，
    //导致下一个链接没有回调函数可用了
    void setAllCallback(const TcpConnectionCallback &cb1,
                        const TcpConnectionCallback &cb2,
                        const TcpConnectionCallback &cb3
                        )
    {
        _onConnecton = cb1;
        _onMessage = cb2;
        _onClose = cb3;
    }
#endif 
    void handleNewConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();

private:
    InetAddress getLocalAddr();
    InetAddress getPeerAddr();

private:
    Socket                  _sock;//这个连接的fd,通过accept获得
    SocketIO                _sockio;//
    InetAddress             _localAddr;//本机地址和端口
    InetAddress             _peerAddr;//对方地址和端口

    TcpConnectionCallback   _onConnecton;//处理连接完成时的函数
    TcpConnectionCallback   _onMessage;//处理接受消息的函数
    TcpConnectionCallback   _onClose;//处理连接断开时的函数
};

}

#endif

